﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using mbine.msgc.model;
using Newtonsoft.Json;

namespace mbine.msgc.forms
{
    public sealed class CChatContainer
    {
        static CChatContainer instance = null;
        static readonly object padlock = new object();

        public List<IRoom> Chats = new List<IRoom>();

        CChatContainer()
        {
        }

        public static CChatContainer Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new CChatContainer();
                    }
                    return instance;
                }
            }
        }

        public IRoom ChatReceive(CRelayMessage msg)
        {
            IRoom room = FindRoom(msg.roomkey, msg.sender);
            if (room == null)
            {
                return null;
            }
            else
            {
                room.GetMessage(msg);
                return room;
            }
        }

        /// <summary>
        /// roomkey를 이용해서 Chat Room을 찾는다. 없는 경우, 새로 생성.
        /// </summary>
        /// <param name="_roomkey"></param>
        /// <param name="_senderemail"></param>
        /// <returns></returns>
        private IRoom FindRoom(string _roomkey, string _senderemail)
        {
            foreach (IRoom room in Chats)
            {
                if (room.CommonKey == _roomkey)
                    return room;
            }
            return null;
            //return Add(new List<IUser> { CRoster.Instance.GetUser(_senderemail) }, _roomkey);
        }

        #region Room Add
        public IRoom Add()
        {
            Chat chat = new Chat();
            Chats.Add(chat);
            chat.Show();

            return chat;
        }

        public IRoom Add(List<IUser> _users)
        {
            IRoom room = Add();
            room.Add(_users);
            return room;
        }

        public IRoom Add(List<IUser> _users, string _roomkey)
        {
            IRoom room = Add(_users);
            room.Add(_users);
            room.CommonKey = _roomkey;
            return room;
        }
        #endregion
    }
}
